import time
import logging

from mongoengine import connect

from app.config.settings import CLOUDMONITOR_MONGODB, CLOUDMONITOR_DB
from app.libs.utils import enable_task_group, utc_now
from app.db.models.asset_tasks import AssetTasks
from app.db.models.balances import Balances

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

connect(db=CLOUDMONITOR_DB, host=CLOUDMONITOR_MONGODB)


def main():
    users = Balances.objects.only("uid").find({
        "planExpireTime": {
            "$gt": utc_now()
        }
    }).distinct("uid")
    collection = AssetTasks._get_collection()
    for _asset_task in collection.find(
        {
            "uid":
                {
                    "$in": users
                },
            "triggerType": "schedule",
            "taskGroupType": "web_security",
            "enableMonitor": True
        }
    ):
        asset_task = AssetTasks.from_dict(_asset_task)
        print("now processing asset task: {}, target: {}".format(asset_task.id, asset_task.targetUrl))
        process_with_retry(enable_task_group, 3, asset_task, insert=False, immediate_exec=False)
        print("asset task: {} processed".format(asset_task.id))
        time.sleep(1)


def process_with_retry(func, retry=3, *args, **kwargs):
    for i in range(retry):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print("retrying {} time(s)".format(i + 1))
            continue


if __name__ == '__main__':
    main()
